package com.luo.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.luo.dao.MemberDao;
import com.luo.pojo.Member;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author Zoro
 * @date 2021年08月30
 */
@Service(interfaceClass = MemberService.class)
@Transactional(readOnly = true)
public class MemberServiceImpl implements MemberService {

    @Autowired
    private MemberDao memberDao;


    @Override
    public Member findByTel(String telephone) {
        return memberDao.getMemberByTel(telephone);
    }

    @Override
    @Transactional(readOnly = false)
    public void addMember(Member newMember) {
        memberDao.addMember(newMember);
    }

    @Override
    public List<Integer> getMemberReport(List<String> dateList) {
        List<Integer> counts = new ArrayList<>();
        //循环查询（大忌讳）
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        if (dateList != null && dateList.size() > 0) {
            for (String date : dateList) {
                int days = 0;
                try {
                    days = getDaysOfMonth(sdf.parse(date));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                date = date + "-" + days;
                Integer count = memberDao.getMemberReport(date);
                counts.add(count);
            }
        }
        return counts;
    }

    @Override
    public Integer getTodayNewMember(String date) {
        return memberDao.getTodayNewMember(date);
    }

    @Override
    public Integer getTotalMember() {
        return memberDao.getTotalMember();
    }

    @Override
    public Integer startEndSelect(String weekMonday, String weekSunday) {
        return memberDao.startEndSelect(weekMonday, weekSunday);
    }


    /**
     * 根据date获取当月的天数
     */
    private static int getDaysOfMonth(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
    }

}
